import 'dart:convert';
import 'package:flutter/material.dart';

import 'package:flutter/services.dart';
import 'package:orientation/orientation.dart';

import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_demo_app/http/HttpController.dart';
import 'package:flutter_demo_app/transition_page.dart';

import 'package:flutter_screenutil/flutter_screenutil.dart';


class betterLogin extends StatefulWidget {
  betterLogin({Key key, this.title}) : super(key: key);
  final String title;

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _betterLoginView();
  }
}

class _betterLoginView extends State<betterLogin> {
  String userName;
  String userPwd;

  //表单状态
  final _formKey = GlobalKey<FormState>();

  @override
  void initState() {
    super.initState();

    OrientationPlugin.forceOrientation(DeviceOrientation.portraitUp);

    SystemChrome.setPreferredOrientations(
        [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);
  }

  @override
  void dispose() {
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
    ]);
    OrientationPlugin.forceOrientation(DeviceOrientation.portraitUp);
    super.dispose();
  }

  /*
  加密
  */
  _encrypt(String str) {
    var c = String.fromCharCode(str.codeUnitAt(0) + str.length);
    for (var i = 1; i < str.length; i++) {
      c += String.fromCharCode(str.codeUnitAt(i) + str.codeUnitAt(i - 1));
    }
    return Uri.encodeComponent(c);
  }

  Future saveString(data_key, Map data) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    sharedPreferences.setString(data_key, json.encode(data)); //存储对象
    print('存储成功');
  }

// POST 请求
  _handleAddShelf() async {
    Map<String, String> map = new Map();
    map["mobile"] = userName;
    map["password"] = userPwd;

    HttpController.post(
        "https://www.bettermorph.com/micoservcice/user/studentlogin/checkStudentLogin",
        (data) {
      if (data != null) {
        final body = json.decode(data.toString()); //接口返回的数据
        final feeds = body["obj"];
        print('feedsd');
        print(feeds['code']);

        if (feeds['code'] == 1005) {
          //存储用户信息
          saveString('user_data', feeds['data']);
          print("feeds['data']");
          print(feeds['data']);
          //页面跳转
          Navigator.push(
              context,
              new MaterialPageRoute(
                  builder: (context) => new transitionPage()));
        }
      }
    }, params: map);
  }

  //学生 账号：13810950101  密码：123456

  void check() {
    var loginForm = _formKey.currentState;
    //验证表单
    if (loginForm.validate()) {
      loginForm.save();
      _handleAddShelf();
      // Fluttertoast.showToast(msg: '信息提交成功',toastLength: Toast.LENGTH_LONG,gravity: ToastGravity.BOTTOM,textColor: Colors.white);
    }
  }

  @override
  Widget build(BuildContext context) {

    //设置字体大小根据系统的“字体大小”辅助选项来进行缩放,默认为false
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334, allowFontScaling: true)..init(context);

    print('设备宽度:${ScreenUtil.screenWidth}'); //Device width
    print('设备高度:${ScreenUtil.screenHeight}'); //Device height
    print('设备的像素密度:${ScreenUtil.pixelRatio}'); //Device pixel density
    print(
        '底部安全区距离:${ScreenUtil.bottomBarHeight}'); //Bottom safe zone distance，suitable for buttons with full screen
    print(
        '状态栏高度:${ScreenUtil.statusBarHeight}px'); //Status bar height , Notch will be higher Unit px

    print('实际宽度的dp与设计稿px的比例:${ScreenUtil.getInstance().scaleWidth}');
    print('实际高度的dp与设计稿px的比例:${ScreenUtil.getInstance().scaleHeight}');

    print(
        '宽度和字体相对于设计稿放大的比例:${ScreenUtil.getInstance().scaleWidth * ScreenUtil.pixelRatio}');
    print(
        '高度相对于设计稿放大的比例:${ScreenUtil.getInstance().scaleHeight * ScreenUtil.pixelRatio}');
    print('系统的字体缩放比例:${ScreenUtil.textScaleFactory}');


    // TODO: implement build
    return Scaffold(
//      appBar: new AppBar(
//        backgroundColor: Colors.deepOrange,
//        elevation: 0.0,
//        title: new Text(
//          "百特英语",
//          style: new TextStyle(
//              color: Colors.white,
//              fontSize: 18.0,
//              fontWeight: FontWeight.normal),
//        ),
//      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Container(
          padding: const EdgeInsets.all(50.0),
          decoration: new BoxDecoration(
            color: Colors.white,
          ),
          alignment: Alignment.center,
          child: new Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                new Container(
                    margin: new EdgeInsets.fromLTRB(50, 0, 50, 20),
                    child: Image.network(
                        "https://www.bettermorph.com/assets/img/logo-color.dc4b5ddd.png")),
                new Form(
                  key: _formKey,
                  child: new Column(
                    children: <Widget>[
                      new Container(
                        height: 50,
                        margin: new EdgeInsets.fromLTRB(0, 20, 0, 20),
                        child: new TextFormField(
                          decoration: new InputDecoration(
                            // labelText: '请输入用户名',
                            border: OutlineInputBorder(
                              borderSide: BorderSide(color: Colors.red),
                            ),
                            contentPadding: EdgeInsets.fromLTRB(16, 10, 0, 10),
                            hintText: '请输入用户名',
                            hintStyle: new TextStyle(
                              fontSize: ScreenUtil.getInstance().setSp(30.0),
                              color: Colors.black38,
                              textBaseline: TextBaseline.alphabetic,
                            ),
                          ),
                          validator: (value) {
                            return value.trim().length > 0 ? null : '用户名不能为空';
                          },
                          onSaved: (value) {
                            userName = value;
                            print(userName);
                          },
                        ),
                      ),
                      new Container(
                        height: 50,
                        child: new TextFormField(
                          decoration: new InputDecoration(
                            border: OutlineInputBorder(
                              borderSide:
                                  BorderSide(color: Colors.red, width: 1.0),
                            ),
                            contentPadding: EdgeInsets.fromLTRB(16, 10, 0, 10),
                            hintText: '请输入密码',
                            hintStyle: new TextStyle(
                              fontSize: 16,
                              color: Colors.black38,
                              textBaseline: TextBaseline.ideographic,
                            ),
                          ),
                          obscureText: true,
                          validator: (value) {
                            return value.length < 6 ? '密码长度不够6位' : null;
                          },
                          onSaved: (value) {
                            userPwd = _encrypt(value);
                            print(userPwd);
                          },
                        ),
                      ),
                    ],
                  ),
                ),
                new Container(
                  margin: new EdgeInsets.fromLTRB(0, 20, 0, 20),
                  width: 200,
                  height: 50,
                  child: new SizedBox(
                    child: new RaisedButton(
                      onPressed: check,
                      color: Colors.deepOrange,
                      child: new Text(
                        '登录',
                        style: new TextStyle(fontSize: 20, color: Colors.white),
                      ),
                    ),
                  ),
                ),
                // Text('$userData.')
              ]),
        ),
      ),
    );
  }
}
